var parentData, parentActive;
layui.use(['form', 'layer'], function () {
	var form = layui.form,
		$ = layui.$;

	var imgArtwork, imgUrl;
	window.active = {};
	//操作
	$('.layui-btn').on('click', function () {
		var type = $(this).data('type');
		active[type] ? active[type].call(this) : '';
	});

	//延时初始化，确保数据已经塞进来了
	setTimeout(() => {
		if (!parentData) return;
		//初始化数据
		form.val("dataform", JSON.parse(JSON.stringify(parentData)));
		if (parentData.headurl) {
			imgUrl = parentData.headurl;
			$(".pic-cont").css('background-size', 'cover');
			$(".pic-cont").css('background-image', 'url(' + parentData.headurl + ')');
		}
	}, 200);

	form.verify({});

	form.on("submit(save)", element => {
		if (js.isNullOrUndefined(imgArtwork) && js.isNullOrUndefined(imgUrl)) {
			top.layer.msg('请上传banner', {
				icon: 2,
				time: 1000 //2秒关闭（如果不配置，默认是3秒）
			});
			return false;
		}
		(async function () {
			let data = form.val("dataform");
			if (!js.isNullOrUndefined(imgArtwork) && imgUrl != imgArtwork.path) {
				const formData = new FormData();
				var nameImg = new Date().getTime() + '.jpg';
				formData.append('file', imgArtwork, nameImg);
				let res = await ajaxAsyncNoTip('upload', formData, 'POST', () => { }, { // 请求后台接口
					processData: false,
					contentType: false
				});

				if (res.upload_files.length) {
					let resImg = res.upload_files[0];
					if (resImg.code != 0) {
						top.layer.alert(resImg.msg + ":" + resImg.info);
						return;
					}
					else {
						imgUrl = resImg.data.imgPath;
					}
				} else {
					top.layer.alert('上传banner失败');
					return;
				}
			}

			data.headurl = imgUrl;
			popSubmit('robot', data);
		})();
		return false;
	});

	$('.pic-cont').click(function () {
		document.getElementById('J-update-img-file').click();
	});
	$('#J-update-img-file').on('change', async function (e) {
		if (!this.files[0] || !window.FileReader) return;
		if (this.files[0].type !== 'image/jpeg') {
			alert('请选择jpg格式的图片!');
			return;
		}

		imgArtwork = await ci.compressImg(this.files[0], {
			size: 0.5,
			Square: true
		});
		imgArtwork.path = URL.createObjectURL(imgArtwork);
		imgArtwork.name = this.files[0].name;
		$(".pic-cont").css('background-size', 'cover');
		$(".pic-cont").css('background-image', 'url(' + imgArtwork.path + ')');
		return;
	});
});